package com.silverbox.sweeporder.controller.member;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.shopper.entity.ShopperExtend;
import com.silverbox.waimai.dubboApi.member.MemberServiceApi;
import com.silverbox.waimai.dubboApi.payMotion.PayMotionApi;
import com.silverbox.waimai.entity.ReceiverAddress;
import com.silverbox.waimai.entity.TakeOutConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.HttpUtils;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.entity.ShopperConfig;
import com.silverbox.sweeporder.common.CommonConstants;
import com.silverbox.sweeporder.common.util.MD5;
import com.silverbox.sweeporder.controller.index.vo.MemberInfoVO;
import com.silverbox.sweeporder.controller.member.vo.BindingUserEntryVO;
import com.silverbox.sweeporder.controller.member.vo.EmployeeAuthRecordEntryVO;
import com.silverbox.sweeporder.controller.member.vo.FindEmployeeEntryVO;
import com.silverbox.sweeporder.controller.member.vo.MemberPointsEntryVO;
import com.silverbox.sweeporder.controller.member.vo.MemberPointsVO;
import com.silverbox.sweeporder.controller.member.vo.SendCodeEntryVO;
import com.silverbox.sweeporder.controller.member.vo.UserBlanceEntryVO;
import com.silverbox.sweeporder.service.employee.EmployeeService;
import com.silverbox.sweeporder.service.index.IndexService;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import com.silverbox.waimai.entity.Waimai;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * Title:MemberController Description:会员接口
 * 
 * @author YaoXuYang
 * @date 2018年1月15日 下午2:45:15
 */
@Controller
@RequestMapping("member")
@Api(tags = { "会员接口" })
@CrossOrigin
public class MemberController {

	private static Logger logger = LoggerFactory.getLogger(MemberController.class);
	
	@Value("${member.url}")
	private String memberUrl;

	@Value("${customCommonCode}")
	private String customCommonCode;

	@Value("${customSpecialCode}")
	private String customSpecialCode;

	@Value("${customPublicKey}")
	private String customPublicKey;

    @Autowired
    private MemberServiceApi memberServiceApi;

	@Value("${sweepOrder.APP_ID}")
	private String SWEEP_APP_ID;

	@Value("${wechat.APP_ID}")
	private String WECHAT_APP_ID;

	@Value("${memberPoints.url}")
	private String memberPointsUrl;
	@Autowired
	private IndexService indexService;
    @Autowired
    private ShopperInfoServiceApi shopperInfoServiceApi;
	@Autowired
	private WaimaiOrderService waimaiOrderService;
	@Autowired
    private PayMotionApi payMotionApi;
	
	@Autowired
	private EmployeeService employeeService;

	/**
	 * 绑定会员
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "bindingUser", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "绑定会员（可调用）")
	public CoreResponse<String> bindingUser(HttpServletRequest request, HttpSession session,
			@RequestBody(required = true) BindingUserEntryVO dindingUser) {
		CoreResponse<String> result = new CoreResponse<String>();
		Map<String, String> nameValuePair = new HashMap<String, String>();
		if (StringUtils.isEmpty(dindingUser.getBuyerId()) || StringUtils.isEmpty(dindingUser.getMobile())
				|| StringUtils.isEmpty(dindingUser.getCode())) {
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		if(!StringUtils.isEmpty(dindingUser.getOrderNum())){
			Waimai param = new Waimai();
			param.setOrderNum(dindingUser.getOrderNum());
			param.setBuyerPhone(dindingUser.getMobile());
			int count = waimaiOrderService.updateWaimaiByOrderNum(param);
			logger.info("取餐柜绑定手机号===============count"+count+"buyerPhone"+dindingUser.getMobile());
		}
		
		if(StringUtils.isEmpty(dindingUser.getNickName())){
			dindingUser.setNickName("吃货");
		}
		String sign = MD5.md5crypt(customCommonCode + dindingUser.getBuyerId() + customPublicKey + customSpecialCode + dindingUser.getMobile());
		nameValuePair.put("mobile", dindingUser.getMobile());
		nameValuePair.put("alipayUserId", dindingUser.getBuyerId());
		nameValuePair.put("nickName", dindingUser.getNickName());
		nameValuePair.put("code", dindingUser.getCode());
		nameValuePair.put("isAlreadyRegistered", dindingUser.getAlreadyRegistered() + "");
		nameValuePair.put("uid", dindingUser.getUid());
		//update by ywc 2019年8月14日 	亚心医院需求，扫码点餐增加员工验证
		if (!Utils.isEmpty(dindingUser.getIsVerifyEmploye()) && "1".equals(dindingUser.getIsVerifyEmploye())) {
			nameValuePair.put("outerSupportId", "isVerifyEmploye");
		} else {
			nameValuePair.put("outerSupportId", "5");
		}
		nameValuePair.put("sign", sign);
 
		 result = HttpUtils.doPostForm(memberUrl + "/waiMaiInterface/bindingUser.htm",
				nameValuePair, 60000, 60000, "UTF-8");
		logger.info("会员=======================+"+nameValuePair+"result=================="+JSONObject.toJSONString(result));
		if (null != result && !Utils.isEmpty(result.getData())) {
			JSONObject jo = JSONObject.parseObject(result == null ? null : result.getData());
			MemberInfoVO userInfo = new MemberInfoVO();
			if (jo.getBooleanValue("success")) {
				userInfo.setMobile(jo.getString("mobile"));
				userInfo.setUid(jo.getString("uid"));
				userInfo.setBinding(true);
				//保存授权信息
				if (!Utils.isEmpty(dindingUser.getIsVerifyEmploye()) && "1".equals(dindingUser.getIsVerifyEmploye())) {
					String userAgent = request.getHeader("User-Agent").toLowerCase();
					Integer clientType = Utils.getClientType(userAgent);
					//授权来源默认为支付宝
					String source = CommonConstants.EmployeeAuthSource.ALIPAY.getValue();
					String appId = SWEEP_APP_ID;
					if (clientType == 3) {
						source = CommonConstants.EmployeeAuthSource.WEIXIN.getValue();
						appId = WECHAT_APP_ID;
					}
					//先查询是否存在员工授权记录
					CoreResponse<EmployeeAuthRecordEntryVO> employeeAuth = indexService.isExistEmployeeAuthRecord(dindingUser.getShopperId(), dindingUser.getStoreId(),source,appId,dindingUser.getBuyerId(), 1);
					Integer employeeAuthId = null;
					if(employeeAuth.getData().getIsExist()){
						employeeAuthId = employeeAuth.getData().getEmployeeAuthRecordId();
					}
					/*if (employeeAuth.getBooleanValue("success") && employeeAuth.getBooleanValue("isExist")) {
						employeeAuthId = employeeAuth.getInteger("id");
					}*/
					indexService.saveOrUpdateEmployeeAuthRecord(employeeAuthId, dindingUser.getShopperId(), dindingUser.getStoreId(), dindingUser.getEmployeeId(), source, appId, dindingUser.getBuyerId());
				}
				return result;
			}else{
				result.setStatusInfo(CoreResponse.StatusInfo.BUSINESS);
				result.setMsg("绑定会员失败");
				return result;
			}
		}else{
			result.setStatusInfo(CoreResponse.StatusInfo.BUSINESS);
			result.setMsg("绑定会员失败");
			return result;
		}
	}
	
	/**
	 * 发送注册验证码
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "sendCode", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发送注册验证码（可调用）")
	public CoreResponse<String> sendCode(HttpServletRequest request, HttpSession session,
			@RequestBody (required = true) SendCodeEntryVO sendCodeEntry) {
		
		CoreResponse<String> result = new CoreResponse<String> ();
		if(StringUtils.isEmpty(sendCodeEntry.getMobile())){
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		Map<String, String> nameValuePair = new HashMap<String, String>();
		String sign = MD5.md5crypt(customCommonCode + sendCodeEntry.getMobile() + customPublicKey + customSpecialCode);
		nameValuePair.put("mobile", sendCodeEntry.getMobile());
		nameValuePair.put("shopperName", sendCodeEntry.getStoreName());
		nameValuePair.put("outerSupportId", "5");
		nameValuePair.put("sign", sign);
		//update by ywc 2019年8月14日 	亚心医院需求，扫码点餐增加员工验证
		if (!Utils.isEmpty(sendCodeEntry.getIsVerifyEmploye())) {
			nameValuePair.put("isVerifyEmploye", sendCodeEntry.getIsVerifyEmploye());
		}

		result = HttpUtils.doPostForm(memberUrl + "/waiMaiInterface/sendCode.htm", nameValuePair,
				60000, 60000, "UTF-8");
		
		if (null != result && !Utils.isEmpty(result.getData())) {
			JSONObject jo = JSONObject.parseObject(result == null ? null : result.getData());
			jo.remove("code");
			result.setData(jo+"");
			return result;
		}else{
			result.setStatusInfo(CoreResponse.StatusInfo.BUSINESS);
			result.setMsg("发送验证码失败");
			return result;
		}
	}

	/**
	 * 获取会员余额
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getUserBlance", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取会员余额（可调用）")
	public CoreResponse<String> getUserBlance(HttpServletRequest request, HttpSession session,
			@RequestBody(required=true) UserBlanceEntryVO userBlanceEntry) {
		CoreResponse<String> result = new CoreResponse<String>();
		if (userBlanceEntry.getStoreId() == null || userBlanceEntry.getShopperId() == null
				|| StringUtils.isEmpty(userBlanceEntry.getBuyerId())) {
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		Integer storeId = userBlanceEntry.getStoreId();
		String buyerId = userBlanceEntry.getBuyerId();
		Integer shopperId = userBlanceEntry.getShopperId();

		Map<String, String> nameValuePair = new HashMap<String, String>();
		//查询会员连锁店
		ShopperConfig shopperConfig = indexService.getShopperConfig(storeId,"CTR_VIP_CHAIN_STORE");
		String chainStoreConfig = (shopperConfig == null || shopperConfig.getPropValue() == null) ? "0"
				: String.valueOf(shopperConfig.getPropValue());

		String sign = MD5.md5crypt(customCommonCode + buyerId + customPublicKey + customSpecialCode + storeId);
		nameValuePair.put("shopperId", storeId + "");
		nameValuePair.put("alipayUserId", buyerId);
		nameValuePair.put("shopperPId", shopperId + "");
		nameValuePair.put("isChainStore", chainStoreConfig);
		nameValuePair.put("sign", sign);
		result = HttpUtils.doPostForm(memberUrl + "/waiMaiInterface/getBlanceByAlipayUserId.htm",
				nameValuePair, 60000, 60000, "UTF-8");
		if (null == result || Utils.isEmpty(result.getData())) {
			result.setStatusInfo(CoreResponse.StatusInfo.BUSINESS);
			result.setMsg("会员信息不存在");
		}
		return result;
	}

    public static void main(String[] args) {
        Map<String, String> nameValuePair = new HashMap<String, String>();

        String sign = MD5.md5crypt("yCt6bSNhbcYVIg" + "2088902014997182" + "8er45fUfD15545qwwt23G" +  "*#06#8e" + "550919");
        nameValuePair.put("shopperId",  "550919");
        nameValuePair.put("alipayUserId", "2088902014997182");
        nameValuePair.put("shopperPId",   "550912");
        nameValuePair.put("isChainStore", "0");
        nameValuePair.put("sign", sign);
        logger.info("nameValuePair = "+nameValuePair.toString());
        CoreResponse<String> result = HttpUtils.doPostForm(  "http://test.blibao.com/member/waiMaiInterface/getBlanceByAlipayUserId.htm",nameValuePair, 60000, 60000, "UTF-8");
        System.out.println(result.getData());
	}

	/**
	 * 获取会员积分信息
	 *
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getMemberPoints", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取会员积分（可调用）")
	public CoreResponse<MemberPointsVO> getMemberPoints(HttpServletRequest request, HttpSession session,
			@RequestBody(required=true) MemberPointsEntryVO memberPointsEntry) {
		CoreResponse<MemberPointsVO> result = new CoreResponse<MemberPointsVO>();
		MemberPointsVO memberPointsVO = new MemberPointsVO();
		CoreResponse<String> tokenResult = new CoreResponse<String>();
		if (memberPointsEntry.getStoreId() == null || memberPointsEntry.getShopperId() == null
				|| StringUtils.isEmpty(memberPointsEntry.getBuyerId()) || StringUtils.isEmpty(memberPointsEntry.getUid())) {
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		Integer storeId = memberPointsEntry.getStoreId();
		String buyerId = memberPointsEntry.getBuyerId();
		Integer shopperId = memberPointsEntry.getShopperId();

		Map<String, String> nameValuePair = new HashMap<String, String>();

		nameValuePair.put("uid", memberPointsEntry.getUid());
		nameValuePair.put("shopper_id", String.valueOf(shopperId));
		nameValuePair.put("openid", buyerId);
		nameValuePair.put("jump_type", "sweepApplet");
		tokenResult = HttpUtils.doPostJson(memberPointsUrl + "/login/loginByUid",
				JSONObject.toJSONString(nameValuePair), 60000, 60000, "UTF-8");
		logger.info("会员获取token=======================+"+nameValuePair+"result=================="+JSONObject.toJSONString(tokenResult));
		if (null != tokenResult && !Utils.isEmpty(tokenResult.getData())) {
			if(JSONObject.parseObject(tokenResult.getData()).get("data") == null){
				result.setStatusInfo(StatusInfo.SUCCESS);
				return result;
			}
			Map<String, String> queryMember = new HashMap<String, String>();
			JSONObject json = JSONObject.parseObject(JSONObject.parseObject(tokenResult.getData()).get("data").toString());
			String token =  json.get("token") == null?"":json.get("token").toString();
			queryMember.put("uid", memberPointsEntry.getUid());
			queryMember.put("shopper_id", String.valueOf(shopperId));
			queryMember.put("store_id",String.valueOf(storeId) );
			queryMember.put("token",token);
			queryMember.put("invokeSources", "2303");
			String url = memberPointsUrl + "/memberCard/queryMemberCardTemplate";
			// 创建POST请求对象
			Map<String, String> headerMap = new HashMap<String,String>();
			headerMap.put("token",token);
			headerMap.put("invoke_source", "2303");
			CoreResponse<String>  memberInfoResult =  HttpUtils.doPostJsonAddHeader(url,JSONObject.toJSONString(queryMember),headerMap, 60000, 60000, "UTF-8");
			logger.info("会员获取积分优惠券信息=======================+"+queryMember+"result=================="+JSONObject.toJSONString(memberInfoResult));
			if(null != memberInfoResult && !Utils.isEmpty(memberInfoResult.getData())){
				if(JSONObject.parseObject(memberInfoResult.getData()).get("data") == null){
					result.setStatusInfo(StatusInfo.SUCCESS);
					return result;
				}
				JSONObject memberInfoJson = JSONObject.parseObject(JSONObject.parseObject(memberInfoResult.getData()).get("data").toString());
				memberPointsVO.setScore(memberInfoJson.get("tally_score_amount") == null ? 0 : Double.valueOf(memberInfoJson.get("tally_score_amount").toString()));
				memberPointsVO.setTallyAmount(memberInfoJson.get("tally_amount") == null ? 0 : Double.valueOf(memberInfoJson.get("tally_amount").toString()));
				memberPointsVO.setVoucherNum(memberInfoJson.get("voucher_num") == null ? 0 : Integer.valueOf(memberInfoJson.get("voucher_num").toString()));
			}
			result.setData(memberPointsVO);
			result.setStatusInfo(CoreResponse.StatusInfo.SUCCESS);
			return result;
		}else{
			result.setStatusInfo(CoreResponse.StatusInfo.BUSINESS);
			result.setMsg("会员信息不存在");
			return result;
		}
	}

    /*
     *<pre>
     * 说    明: 新增收货地址
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-03-06 18:00
     *</pre>
     **/
    @RequestMapping(value = "addOrUpdateReceiverAddress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增或更新用户收货地址")
    public CoreResponse<Object> addOrUpdateReceiverAddress(ReceiverAddress receiverAddress) {
        CoreResponse<Object> res = new CoreResponse<>();
        res.setCode(StatusInfo.FORBIDDEN.getCode());
        if(StringUtils.isEmpty(receiverAddress.getReceiverName())){
            res.setSubMsg("收货人姓名不能为空");
            return res;
        }
        if(receiverAddress.getReceiverSex() == null){
            res.setSubMsg("收货人性别不能为空");
            return res;
        }
        if(StringUtils.isEmpty(receiverAddress.getReceiverTel())){
            res.setSubMsg("收货人手机号不能为空");
            return res;
        }
        if(StringUtils.isEmpty(receiverAddress.getReceiverAddress())){
            res.setSubMsg("收货人地址不能为空");
            return res;
        }
        if(StringUtils.isEmpty(receiverAddress.getReceiverAddressDetail())){
            res.setSubMsg("收货人详细地址不能为空");
            return res;
        }
        if(StringUtils.isEmpty(receiverAddress.getReceiverLng()) || StringUtils.isEmpty(receiverAddress.getReceiverLat())){
            res.setSubMsg("收货人经纬度不能为空");
            return res;
        }
        if(StringUtils.isEmpty(receiverAddress.getThirdUserId())){
            res.setSubMsg("thirdUserId不能为空");
            return res;
        }
        receiverAddress.setIsDefault(receiverAddress.getIsDefault() == null ? 0 : receiverAddress.getIsDefault());
        return memberServiceApi.addOrUpdateReceiverAddress(receiverAddress);
    }

    /*
     *<pre>
     * 说    明: 删除收货地址
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-03-06 18:00
     *</pre>
     **/
    @RequestMapping(value = "deleteReceiverAddress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除用户收货地址")
    public CoreResponse<Object> deleteReceiverAddress(Integer addressId) {
        CoreResponse<Object> res = new CoreResponse<>();
        res.setCode(StatusInfo.FORBIDDEN.getCode());
        if(addressId == null){
            res.setSubMsg("addressId不能为空");
            return res;
        }
        return memberServiceApi.deleteReceiverAddress(addressId);
    }

    /*
     *<pre>
     * 说    明: 获取收货地址
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-03-06 18:00
     *</pre>
     **/
    @RequestMapping(value = "findReceiverAddressList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户收货地址")
    public CoreResponse<Object> findReceiverAddressList(String buyerId,Integer pageNo,Integer pageSize,Integer storeId) {
        CoreResponse<Object> res = new CoreResponse<>();
        if(storeId == null){
            res.setCode(CoreResponse.StatusInfo.NORESOURCE.getCode());
            res.setSubMsg("storeId不能为空");
            return res;
        }
        res.setCode(StatusInfo.FORBIDDEN.getCode());
        if(buyerId == null){
            res.setSubMsg("buyerId不能为空");
            return res;
        }
        TakeOutConfig takeOutConfig = shopperInfoServiceApi.getTakeOutConfigByStoreId(storeId);
        if(takeOutConfig == null){
            res.setCode(CoreResponse.StatusInfo.NORESOURCE.getCode());
            res.setSubMsg("商家无外卖配置，获取配送范围失败");
            return res;
        }
        Double maxTakeOutDistance = takeOutConfig.getMaxTakeOutDistance();
        //店铺经纬度
        Double shopLng;
        Double shopLat;
        //根据商家外卖配送方式，取商家经纬度。如果商家设置自配送，则取商家后台设置的经纬度；如果商家设置了第三方配送，则取第三方配送返回的经纬度。
        if (new Integer(0).equals(takeOutConfig.getTakeOutMethod())) {
            ShopperExtend shopperExtend = shopperInfoServiceApi.getShopperExtend(storeId);
            shopLng = shopperExtend.getY();
            shopLat = shopperExtend.getX();
        } else {
            Map<String, Object> shopMap = shopperInfoServiceApi.getShopLatAndLng(storeId, takeOutConfig.getTakeOutMethod());
            if (null == shopMap || null == shopMap.get("lng") || null == shopMap.get("lat") ||
                    Utils.isEmpty(shopMap.get("lng").toString()) || Utils.isEmpty(shopMap.get("lat").toString())) {
                res.setSubMsg("数据异常");
                res.setCode(CoreResponse.StatusInfo.NORESOURCE.getCode());
                return res;
            } else {
                shopLng = Double.valueOf(shopMap.get("lng").toString());
                shopLat = Double.valueOf(shopMap.get("lat").toString());
            }
        }
        if (null == shopLng || null == shopLat) {
            res.setSubMsg("获取商家坐标失败，计算失败");
            res.setCode(CoreResponse.StatusInfo.NORESOURCE.getCode());
            return res;
        }
        return memberServiceApi.findReceiverAddressList(buyerId,pageNo,pageSize,maxTakeOutDistance,shopLng,shopLat);
    }

	/**
	 * 根据mobile获取员工id
	 * @param request
	 * @param session
	 * @return
	 */

	@RequestMapping(value = "getShopEmployeeIdByMobile", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据mobile获取员工id（可调用）")
	public CoreResponse<FindEmployeeEntryVO> getShopEmployeeIdByMobile(HttpServletRequest request, HttpSession session,@RequestParam(required = false) Integer storeId, @RequestParam(required = true) Integer shopperId, @RequestParam(required = true) String phone) {
		CoreResponse<FindEmployeeEntryVO> result = new CoreResponse<FindEmployeeEntryVO>();
		if (StringUtils.isEmpty(phone) || shopperId==null) {
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		result = indexService.getShopEmployeeIdByMobile(shopperId, storeId, phone);

		return result;
	}

/*	*//**
	 *
	 *//*
	*//**
	 * 保存员工授权记录
	 * @param request
	 * @param session
	 * @param shopId
	 * @param storeId
	 * @param employeeId
	 * @param buyerId
	 * @return
	 *//*
	@RequestMapping(value = "saveEmployeeAuthRecord", method = RequestMethod.POST)
    @ResponseBody
    //@ApiOperation(value = "保存授权记录（可调用）")
	public CoreResponse<String> saveEmployeeAuthRecord(HttpServletRequest request, HttpSession session,@RequestBody(required=true) EmployeeAuthRecordEntryVO  employeeAuthRecordEntryInteger shopId, Integer storeId, Integer employeeId, String buyerId) {
		CoreResponse<String> result = new CoreResponse<String>();
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isEmpty(employeeAuthRecordEntry.getBuyerId()) || employeeAuthRecordEntry.getEmployeeId()==null || employeeAuthRecordEntry.getShopId()==null || employeeAuthRecordEntry.getStoreId()==null){
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		Integer clientType = Utils.getClientType(userAgent);
		//授权来源默认为支付宝
		String source = CommonConstants.EmployeeAuthSource.ALIPAY.getValue();
		String appId = SWEEP_APP_ID;
		if (clientType == 3) {
			source = CommonConstants.EmployeeAuthSource.WEIXIN.getValue();
			appId = WECHAT_APP_ID;
		}
		Integer shopId=employeeAuthRecordEntry.getShopId();
		Integer storeId=employeeAuthRecordEntry.getStoreId();
		Integer employeeId=employeeAuthRecordEntry.getEmployeeId();
		String buyerId=employeeAuthRecordEntry.getBuyerId();
		//先查询是否存在员工授权记录
		JSONObject employeeAuth = employeeService.isExistEmployeeAuthRecord(shopId, storeId,source,appId,buyerId, 1);
		Integer employeeAuthId = null;
		if (employeeAuth.getBooleanValue("success") && employeeAuth.getBooleanValue("isExist")) {
			employeeAuthId = employeeAuth.getInteger("id");
		}
		Boolean isSaveEmployeeAuthRecord = employeeService.saveOrUpdateEmployeeAuthRecord(employeeAuthId, shopId, storeId, employeeId, source, appId, buyerId);
		if(isSaveEmployeeAuthRecord){
			jsonObject.put("employee_id", employeeId);
			jsonObject.put("success", true);

		}else{
			jsonObject.put("success", false);
			result.setMsg("保存员工授权失败");

		}
		result.setData(JSON.toJSONString(jsonObject));
		return result;
	}*/

	/**
	 * 查询员工授权记录
	 *
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "findEmployeeAuthRecord", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询员工授权记录（可调用）")
	public CoreResponse<EmployeeAuthRecordEntryVO> findEmployeeAuthRecord(HttpServletRequest request, HttpSession session,@RequestParam(required = true) Integer storeId,@RequestParam(required = true) Integer shopperId, @RequestParam(required = true) String buyerId) {
		CoreResponse<EmployeeAuthRecordEntryVO> result = new CoreResponse<EmployeeAuthRecordEntryVO>();
		if (StringUtils.isEmpty(buyerId) || shopperId == null
				|| storeId == null) {
			result.setStatusInfo(StatusInfo.ERROR_40002);
			return result;
		}
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		Integer clientType = Utils.getClientType(userAgent);
		//授权来源默认为支付宝
		String source = CommonConstants.EmployeeAuthSource.ALIPAY.getValue();
		String appId = SWEEP_APP_ID;
		if (clientType == 3) {
			source = CommonConstants.EmployeeAuthSource.WEIXIN.getValue();
			appId = WECHAT_APP_ID;
		}
		// 先查询是否存在员工授权记录
		result= indexService.isExistEmployeeAuthRecord(shopperId, storeId, source, appId, buyerId, 1);
		/*if (employeeAuth.getBooleanValue("success")) {
			result.setData(employeeAuth);
		} else {
			result.setMsg("查询员工授权信息失败");
		}*/
		return result;
	}

	/*
	 *<pre>
	 * 说    明: 查询会员可抵扣金额
	 * 涉及版本:
	 * 创 建 者: YangYangjun
	 * 日    期: 2020-07-09 00:13
	 *</pre>
	 **/
    @RequestMapping(value = "getMemberDeductibleScore", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询会员可抵扣金额")
    public CoreResponse<Object> getMemberDeductibleScore(Integer storeId,Integer shopId,String uid) {
        CoreResponse<Object> response = new CoreResponse<>();
        if(Utils.isEmpty(storeId) || Utils.isEmpty(shopId) || Utils.isEmpty(uid)){
            response.setMsg("查询失败");
            response.setSubMsg("缺少必填参数");
            return response;
        }
        JSONObject memberDeductibleScore = payMotionApi.getMemberDeductibleScore(shopId, storeId, uid);
        if (Utils.isEmpty(memberDeductibleScore)){
            response.setMsg("查询失败");
            response.setSubMsg("积分抵扣查询失败");
            return response;
        }
        response.setMsg("查询成功");
        response.setData(memberDeductibleScore);
        return response;
    }


}



